package com.tj.collection.controller.lending;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.tj.collection.aop.anno.VisitorAccessible;
import com.tj.collection.bean.ApiResponse;
import com.tj.collection.db.dao.ClImagesDao;
import com.tj.collection.db.dao.ClReceiverDao;
import com.tj.collection.db.dao.ClReceiverDetailDao;
import com.tj.collection.db.entity.ClReceiverDetailEntity;
import com.tj.collection.db.entity.ClReceiverEntity;
import com.tj.collection.service.AllocationService;
import com.tj.collection.service.request.ClOrderContactsRequest;
import com.tj.collection.service.request.ClOrderReceiveRequest;
import com.tj.collection.service.request.ClRepaymentRequest;
import com.tj.collection.service.request.MoneyUpdateRequest;
import com.tj.collection.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 赵洋～
 * @Description:
 * @Date: Create in 09:56 2019-04-10
 */
@RestController
@RequestMapping("/collection")
public class ClReceiveController {
    private static final Log LOGGER = LogFactory.getLog(ClReceiveController.class);

    @Autowired
    private AllocationService allocationService;

    @Autowired
    private ClReceiverDao receiverDao;

    @Autowired
    private ClReceiverDetailDao receiverDetailDao;


    /**
     * 催收单 收单
     *
     * @param request
     * @return
     */
    @RequestMapping("/receive/order")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse receiveTradePush(@RequestBody ClOrderReceiveRequest request) {
        //新的收单入口
        try {
            allocationService.receiver(request);
        } catch (ApplicationException e) {
            LOGGER.error("催收收单业务处理失败,request:" + JSON.toJSONString(request), e);
            throw e;
        } catch (Exception e) {
            LOGGER.error("催收收单业务处理异常,request:{}", JSON.toJSONString(request), e);
            throw new ApplicationException("催收收单业务处理异常");
        }
        return new ApiResponse<>();
    }

    /**
     * 催收单 收单
     *
     * @param request
     * @return
     */
    @RequestMapping("/receive/order/update")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse receiveTradePushUpdate(@RequestBody ClOrderReceiveRequest request) {
        //新的收单入口
        try {
            allocationService.receiverUpdate(request);
        } catch (ApplicationException e) {
            LOGGER.error("催收收单更新业务处理失败,request:" + JSON.toJSONString(request), e);
            throw e;
        } catch (Exception e) {
            LOGGER.error("催收收单更新异常,request:{}", JSON.toJSONString(request), e);
            throw new ApplicationException("催收收单更新异常");
        }
        return new ApiResponse<>();
    }

    /**
     * 催收 接收通讯录
     *
     * @param request
     * @return
     */
    @RequestMapping("/receive/contacts")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse receiveUserContacts(@RequestBody ClOrderContactsRequest request) {
        //新的收单入口
        try {
            allocationService.saveUserContacts(request);
        } catch (ApplicationException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("新的收单逻辑失败,request:{}", JSON.toJSONString(request), e);
            throw new ApplicationException("催收接收订单异常");
        }
        return new ApiResponse<>();
    }

    /**
     * 还款通知
     *
     * @param request
     * @return
     */
    @RequestMapping("/receive/repayment")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse receiveTradeUpdate(@RequestBody ClRepaymentRequest request) {
        //新的还款通知催收的入口
        try {
            if (StringUtils.isEmpty(request.getOrderBillNo())) {
                request.setOrderBillNo(request.getTradeNo());
            }
            if (request.getPaidType() == 1) {
                allocationService.repaymentUpdate(request);
            } else {
                allocationService.repaymentExtensionUpdate(request);
            }
        } catch (ApplicationException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("新的还款通知催收失败,request:{}", JSON.toJSONString(request), e);
            throw new ApplicationException("催收接收还款通知异常");
        }
        return new ApiResponse();
    }

    @RequestMapping("/receive/remainMoney/update")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse remainMoneyUpdate(@RequestBody MoneyUpdateRequest request) {
        //新的还款通知催收的入口
        ClReceiverEntity receiverEntity = receiverDao.selectLastByBillNo(request.getBillNo());
        if(receiverEntity==null){
            throw new ApplicationException("bill not found");
        }

        ClReceiverDetailEntity clReceiverDetailEntity = receiverDetailDao.selectOneByCollectionNo(receiverEntity.getCollectionNo());
        if(clReceiverDetailEntity==null){
            throw new ApplicationException("bill detail not found");
        }

        clReceiverDetailEntity.setRemainMoney(new BigDecimal(request.getRemainCapital()));
        receiverDetailDao.updateByPrimaryKey(clReceiverDetailEntity);

        return new ApiResponse();
    }

    /**
     * 还款通知
     *
     * @param request
     * @return
     */
    @RequestMapping("/receive/remove")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse receiveRemoveUpdate(@RequestBody ClRepaymentRequest request) {
        //移除订单的接口
        if (StringUtils.isEmpty(request.getTradeNo())) {
            throw new ApplicationException("移除订单的tradeNo为空");
        }

        try {
            allocationService.remove(request);
        } catch (Exception e) {
            LOGGER.error("receiveRemoveUpdate remove failed,request:{}", JSON.toJSONString(request), e);
            throw new ApplicationException("remove order failed");
        }

        return new ApiResponse();
    }

    @RequestMapping("/receive/recover")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse recover(@RequestBody ClRepaymentRequest request) {
        //移除订单的接口
        if (StringUtils.isEmpty(request.getTradeNo())) {
            throw new ApplicationException("移除订单的tradeNo为空");
        }

        try {
            allocationService.recover(request);
        } catch (Exception e) {
            LOGGER.error("receiveRemoveUpdate remove failed,request:{}", JSON.toJSONString(request), e);
            throw new ApplicationException("remove order failed");
        }

        return new ApiResponse();
    }

    @RequestMapping("/trade/updateActiveReceiver")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse updateActiveReceiver(@RequestBody JSONObject jsonObject) {
        return new ApiResponse(String.valueOf(allocationService.updateActiveReceiver(jsonObject
        )));
    }


    @RequestMapping("/trade/updateActiveReceiverByLogin")
    @ParamsValidate
    @VisitorAccessible
    public ApiResponse updateActiveReceiverByLogin(@RequestBody JSONObject jsonObject) {
        return new ApiResponse(String.valueOf(allocationService.updateActiveReceiverByLogin(jsonObject.getString("mobile"), jsonObject.getString("packageName"), "1")));
    }


    public static void main(String[] args) {
        String[] a1 = {

        };

        Map<String, String> head = new HashMap<>();
        head.put("Content-Type", "application/json");
        for (String a : a1) {
            String[] arr = a.split("\\|");
            String collectionNo = arr[0].trim();
            long id = Long.valueOf(arr[1].trim());
            int num = Integer.valueOf(arr[2].trim());

            JSONObject req = new JSONObject();
            req.put("collectionNo", collectionNo);
            req.put("id", id);
            String resp = HttpUtil.postPageBody("https://admin-api.cashmama.in/collection/invalid", head, req.toJSONString());
            System.out.println("req:" + req.toJSONString() + ", 理论值:" + num + ",   resp:" + resp);

            String[] barr = resp.split(":");
            int num2 = Integer.valueOf(barr[1].replaceAll("\"", ""));
            if (num != num2) {
                throw new RuntimeException("值不相等");
            }
        }

    }
}
